import { defineComponent, ref, h } from 'vue'
import type { Component } from 'vue'
import styles from './index.module.scss'
import { NSelect, NBadge, NAvatar, NDropdown, NIcon } from 'naive-ui'
import {
  PersonCircleOutline as UserIcon,
  Pencil as EditIcon,
  LogOutOutline as LogoutIcon
} from '@vicons/ionicons5'
import { useHeader } from './use-header'
import { useUserStore } from '@/store/user/user'
import elementResizeDetectorMaker from 'element-resize-detector'
import ModPwdModal from '@/views/user/dialog/mod-pwd-modal'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const HeaderBar = defineComponent({
  name: 'HeaderBar',
  components: { ModPwdModal },
  setup() {
    const router = useRouter()

    //获取当前用户所有未归档的项目列表
    const title = import.meta.env.VITE_APP_TITLE
    const {
      variables,
      getProjectOptions,
      switchProject,
      getUnreadCount,
      logout
    } = useHeader()
    getProjectOptions({
      userId: window.$store.state.userInfo.id
    })
    getUnreadCount()
    const currentProjectId = ref()
    currentProjectId.value = window.$store.state.userInfo.currentProjectId
    //切换项目
    const onSwitchProject = (proId: number) => {
      window.$dialog.warning({
        title: window.$t('dialog.warningTitle'),
        content: window.$t('project.switchProjectWarning'),
        positiveText: window.$t('dialog.positiveText'),
        negativeText: window.$t('dialog.negativeText'),
        onPositiveClick: () => {
          switchProject(proId)
        },
        onNegativeClick: () => {
          currentProjectId.value = window.$store.state.userInfo.currentProjectId
        },
        onClose: () => {
          currentProjectId.value = window.$store.state.userInfo.currentProjectId
        }
      })
    }

    //用户栏下拉菜单
    const renderIcon = (icon: Component) => {
      return () => {
        return h(NIcon, null, {
          default: () => h(icon)
        })
      }
    }
    const userDrowOptions = [
      {
        label: window.$t('user.userCenter'),
        key: 'userCenter',
        icon: renderIcon(UserIcon)
      },
      {
        label: window.$t('user.modPwd'),
        key: 'modifyPws',
        icon: renderIcon(EditIcon)
      },
      {
        label: window.$t('user.logout'),
        key: 'logout',
        icon: renderIcon(LogoutIcon)
      }
    ]
    //显示修改密码弹窗
    const showModPwdModalRef = ref(false)
    //用户下拉菜单选择
    const handleSelectUserDrow = (key: string) => {
      switch (key) {
        case 'userCenter':
          router.push({
            path: '/user/userCenter',
            query: {
              tab: window.$t('user.userCenter'),
              tabName: 'UserCenterTab'
            }
          })
          break
        case 'modifyPws':
          showModPwdModalRef.value = true
          break
        case 'logout':
          logout(userStore.getToken)
          //退出登录成功，跳转到登录页
          router.push('/login')
          break
      }
    }

    //点击平台logo,打开首页标签
    const openHomeTab = () => {
      router.push({
        path: '/home',
        query: {
          tab: window.$t('common.home'),
          tabName: 'HomeTab'
        }
      })
    }
    return {
      title,
      variables,
      currentProjectId,
      userDrowOptions,
      onSwitchProject,
      handleSelectUserDrow,
      showModPwdModalRef,
      openHomeTab
    }
  },
  data() {
    return {
      containerWidth: 0
    }
  },
  mounted() {
    const erd = elementResizeDetectorMaker()
    erd.listenTo(this.$refs.containerRef, (el: { offsetWidth: number }) => {
      //当header栏宽度小于666时，隐藏平台标题
      const titleEl = this.$refs.titleRef as HTMLDivElement
      if (el.offsetWidth > 666) {
        titleEl.style.display = 'block'
      } else {
        titleEl.style.display = 'none'
      }
    })
  },
  methods: {
    handleModPwdModalShowChange() {
      this.showModPwdModalRef = !this.showModPwdModalRef
    }
  },
  render() {
    return (
      <div ref='containerRef' class={styles.container}>
        <h2 ref='titleRef' onClick={this.openHomeTab}>
          {this.title}
        </h2>
        <div class={styles.project} title={window.$t('project.currentProject')}>
          <NSelect
            v-model:value={this.currentProjectId}
            size='small'
            options={this.variables.projectOptions}
            onUpdateValue={this.onSwitchProject}
          />
        </div>

        <div class={styles.settings}>
          <div class={styles.msg}>
            <NBadge value={this.variables.unreadCount}>
              <span class={styles.msg_color}>{window.$t('user.msg')}</span>
            </NBadge>
          </div>

          <div class={styles.user}>
            <div class={styles.head}>
              <NAvatar
                round
                size='large'
                lazy
                src={window.$store.state.userInfo.headImgUrl}
              />
            </div>
            <div class={styles.username}>
              <NDropdown
                options={this.userDrowOptions}
                onSelect={this.handleSelectUserDrow}
              >
                <span>{window.$store.state.userInfo.nickname}</span>
              </NDropdown>
              <ModPwdModal
                showModal={this.showModPwdModalRef}
                onModalShowChange={this.handleModPwdModalShowChange}
              ></ModPwdModal>
            </div>
          </div>
        </div>
      </div>
    )
  }
})

export default HeaderBar
